package org.springblade.modules.admin.task.feishu;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.enums.FeiShuDocumentEnum;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.feishu.*;
import org.springblade.modules.admin.service.IElevatorContractService;
import org.springblade.modules.admin.service.feishu.IFeiShuDocumentService;
import org.springblade.modules.admin.vo.feishu.GalaxyElevatorNumVO;
import org.springblade.modules.admin.vo.feishu.LarkContractContinueTimelinessVO;
import org.springblade.modules.admin.vo.feishu.LarkContractLoseRateTrendVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 宇航的合同表格
 * @author: Sharry
 * @createTime: 2025-01-16 15:00
 * @version: Version-1.0
 */
@Component
@Slf4j
public class LarkContractContinueJob {

	@Autowired
	private IElevatorContractService elevatorContractService;

	@Autowired
	private IFeiShuDocumentService feiShuDocumentService;

	@XxlJob("LarkContractContinueJob")
	public void galaxyLarkContractContinueJob() {
		XxlJobHelper.handleSuccess("定时任务覆盖宇航的合同续签表-[执行]开始");
		try{
			// 0. 更新流程：先列出全部记录，获取当前全部record_id 集合。现阶段先删除后新增，则完成更新
			String result = "";
			// 1. 数据准备：目标文件夹Token、文档ID; 需要更新的数据列表
			// 1.1 目标文件夹Token、文档ID
			String appToken = FeiShuDocumentEnum.CONTRACT_CONTINUE.getAppToken();
			String tableId = FeiShuDocumentEnum.CONTRACT_CONTINUE.getTableId();
			List<LarkContractContinueDTO> recordSourceList = elevatorContractService.getLarkContractContinueList();
			// 1.2 数据封装
			FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
			List<UpdateMaintenancePersonnelDTO> records = new ArrayList<>();
			for (LarkContractContinueDTO u : recordSourceList) {
				UpdateMaintenancePersonnelDTO element = new UpdateMaintenancePersonnelDTO();
				Map<String, Object> elementMap = new HashMap<>(10);
				elementMap.put("梯ID", String.valueOf(u.getElevatorId()));
				elementMap.put("项目名称", u.getBuildingName());
				elementMap.put("梯号", u.getElevatorAddress());
				elementMap.put("合同ID（当前）", String.valueOf(u.getContractIdNow()));
				Date contractStartTimeNow = u.getContractStartTimeNow();
				if(!Func.isNull(contractStartTimeNow)){
					elementMap.put("合同开始时间（当前）", contractStartTimeNow.getTime());
				}
				Date contractEndTimeNow = u.getContractEndTimeNow();
				if(!Func.isNull(contractEndTimeNow)){
					elementMap.put("合同结束时间（当前）", contractEndTimeNow.getTime());
				}
				elementMap.put("合同状态（内外）", u.getContractInsuranceStatus());
				elementMap.put("外包状态", u.getOutsourceStatus());
				elementMap.put("合同ID（最新）", String.valueOf(u.getContractIdNew()));
				Date contractStartTimeNew = u.getContractStartTimeNew();
				if(!Func.isNull(contractStartTimeNew)) {
					elementMap.put("合同开始时间（最新）", contractStartTimeNew.getTime());
				}
				Date contractEndTimeNew = u.getContractEndTimeNew();
				if(!Func.isNull(contractEndTimeNew)) {
					elementMap.put("合同结束时间（最新）", contractEndTimeNew.getTime());
				}
				elementMap.put("自己/最后份合同", u.getMaxOne());
				elementMap.put("最新合同是否到期状态", u.getIsExpireNew());
				element.setFields(elementMap);
				records.add(element);
			}
			batchDTO.setRecords(records);
			List<JSONObject> deleteObjects = feiShuDocumentService.commandQueryBatch(appToken, tableId, null);
			// 遍历并获取 jsonObjects 的 封装成 FeiShuBatchDTO 对象
			List<String> r = new ArrayList<>();
			deleteObjects.forEach(j -> r.add(j.getString("record_id")));
			FeiShuBatchDTO deleteFeiShuBatchDTO = new FeiShuBatchDTO();
			deleteFeiShuBatchDTO.setRecords(r);
			// 直接覆盖
			feiShuDocumentService.commandDeleteBatchLimit(appToken, tableId, deleteFeiShuBatchDTO);
			// 新增
			result = feiShuDocumentService.commandAddBatchLimit(appToken, tableId, batchDTO);
			// 3. 发送执行结果消息
			String message = "定时覆盖" + FeiShuDocumentEnum.getDescription(appToken, tableId) + "结果：" + result;
			feiShuDocumentService.commandSendGroupMessage(appToken, tableId, message);
			XxlJobHelper.handleSuccess("定时任务覆盖宇航的合同续签表-[执行]成功");
		}catch (Exception e){
			XxlJobHelper.handleSuccess("定时任务覆盖宇航的合同续签表-[执行]失败"+e);
		}
	}

	/**
	 * 日月周
	 * 定时任务覆盖宇航的及时续约率表
	 */
	@XxlJob("LarkContractContinueTimelinessJob")
	public void galaxyLarkContractContinueTimelinessJob() {
		XxlJobHelper.handleSuccess("定时任务覆盖宇航的及时续约率表-[执行]开始");
		// 1. 数据准备：目标文件夹Token、文档ID; 需要更新的数据列表
		// 获取3个表的Token和tableId
		String dailyAppToken = FeiShuDocumentEnum.CONTRACT_CONTINUE_DAY_DETAIL.getAppToken();
		String dailyTableId = FeiShuDocumentEnum.CONTRACT_CONTINUE_DAY_DETAIL.getTableId();
		String monthlyAppToken = FeiShuDocumentEnum.CONTRACT_CONTINUE_MONTH_DETAIL.getAppToken();
		String monthlyTableId = FeiShuDocumentEnum.CONTRACT_CONTINUE_MONTH_DETAIL.getTableId();
		String weeklyAppToken = FeiShuDocumentEnum.CONTRACT_CONTINUE_WEEK_DETAIL.getAppToken();
		String weeklyTableId = FeiShuDocumentEnum.CONTRACT_CONTINUE_WEEK_DETAIL.getTableId();
		String monthlyLastDateAppToken = FeiShuDocumentEnum.CONTRACT_CONTINUE_MONTH_LAST_DATE.getAppToken();
		String monthlyLastDateTableId = FeiShuDocumentEnum.CONTRACT_CONTINUE_MONTH_LAST_DATE.getTableId();
		String weeklyLastDateAppToken = FeiShuDocumentEnum.CONTRACT_CONTINUE_WEEK_LAST_DATE.getAppToken();
		String weeklyLastDateTableId = FeiShuDocumentEnum.CONTRACT_CONTINUE_WEEK_LAST_DATE.getTableId();
		// 查询数据
		List<LarkContractContinueTimelinessVO> dataSources = elevatorContractService.getLarkContractContinueTimelinessList();
		// 2. 使用公共方法执行数据覆盖
		contractContinueTimelinessSendToLark(dailyAppToken,dailyTableId,dataSources);
		// 3. 若今天是周一,则执行周详情数据表
		Date today = new Date();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(today);
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		// 这个方法的周一是从2开始，周日是1
//		contractContinueTimelinessSendToLark(weeklyAppToken, weeklyTableId,dataSources);
		if(dayOfWeek == 2){
			contractContinueTimelinessSendToLark(weeklyAppToken, weeklyTableId,dataSources);
			contractContinueTimelinessSendLastDayToLark(weeklyLastDateAppToken, weeklyLastDateTableId,dataSources);
		}
		// 4. 若今天是每个月第1天，则执行月详情数据并覆盖
		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
//		contractContinueTimelinessSendToLark(monthlyAppToken, monthlyTableId,dataSources);
		if(dayOfMonth == 1){
			contractContinueTimelinessSendToLark(monthlyAppToken, monthlyTableId,dataSources);
			contractContinueTimelinessSendLastDayToLark(monthlyLastDateAppToken, monthlyLastDateTableId,dataSources);
		}
		try{
			XxlJobHelper.handleSuccess("定时任务覆盖宇航的及时续约率表-[执行]成功");
		}catch (Exception e){
			XxlJobHelper.handleSuccess("定时任务覆盖宇航的及时续约率表-[执行]失败"+e);
		}
	}

	private void contractContinueTimelinessSendLastDayToLark(String appToken, String tableId, List<LarkContractContinueTimelinessVO> dataSources) {
		if(Func.isEmpty(dataSources)){
			return;
		}

		// 数据处理
		FeiShuBatchDTO feishuBatchDTO = new FeiShuBatchDTO();
		List<FeiShuFieldsDTO> records = new ArrayList<>();

		List<Date> lastDate;
		if(FeiShuDocumentEnum.CONTRACT_CONTINUE_WEEK_LAST_DATE.getTableId().equals(tableId)) {
			// 获取这一周的最后
			lastDate = dataSources.stream().map(t -> DateUtil.endOfWeek(t.getRecordDate())).distinct().collect(Collectors.toList());
		}else{
			// 获取这一月是哪个月
			lastDate = dataSources.stream().map(t -> DateUtil.endOfMonth(t.getRecordDate())).distinct().collect(Collectors.toList());
		}
		for (Date d : lastDate) {
			FeiShuFieldsDTO element = new FeiShuFieldsDTO();
			Map<String, Object> elementMap = new HashMap<>(30);
			if(FeiShuDocumentEnum.CONTRACT_CONTINUE_WEEK_LAST_DATE.getTableId().equals(tableId)) {
				// 获取这一周的最后
				Date lastDay = DateUtil.endOfWeek(d);
				elementMap.put("周最后日",lastDay.getTime());
			}else{
				// 获取这一月是哪个月
				Date lastDay = DateUtil.endOfMonth(d);
				elementMap.put("月最后日",lastDay.getTime());
			}
			element.setFields(elementMap);
			records.add(element);
		}
		feishuBatchDTO.setRecords(records);
		String result = feiShuDocumentService.commandCoverBatch(appToken, tableId, feishuBatchDTO);
		String message = "定时覆盖" + FeiShuDocumentEnum.getDescription(appToken, tableId) + "结果：" + result;
		feiShuDocumentService.commandSendGroupMessage(appToken, tableId, message);
	}

	/**
	 * 日月周
	 * 定时任务覆盖宇航的丢保率表
	 */
	@XxlJob("LarkContractLoseRateJob")
	public void galaxyLarkContractLoseRateJob() {
		XxlJobHelper.handleSuccess("定时任务覆盖宇航的丢保率表-[执行]开始");
		try{
			// 1. 数据准备：目标文件夹appToken、文档ID
			// 1.1 三个详情表的 appToken 和 tableId
			String dailyAppToken = FeiShuDocumentEnum.CONTRACT_LOSS_DAY_DETAIL.getAppToken();
			String dailyTableId = FeiShuDocumentEnum.CONTRACT_LOSS_DAY_DETAIL.getTableId();
			String monthlyAppToken = FeiShuDocumentEnum.CONTRACT_LOSS_MONTH_DETAIL.getAppToken();
			String monthlyTableId = FeiShuDocumentEnum.CONTRACT_LOSS_MONTH_DETAIL.getTableId();
			String weeklyAppToken = FeiShuDocumentEnum.CONTRACT_LOSS_WEEK_DETAIL.getAppToken();
			String weeklyTableId = FeiShuDocumentEnum.CONTRACT_LOSS_WEEK_DETAIL.getTableId();

			// 1.2 三个趋势表的appToken和tableId
			String dailyTrendAppToken = FeiShuDocumentEnum.CONTRACT_LOSS_RATE_DAY_TREND.getAppToken();
			String dailyTrendTableId = FeiShuDocumentEnum.CONTRACT_LOSS_RATE_DAY_TREND.getTableId();
			String monthlyTrendAppToken = FeiShuDocumentEnum.CONTRACT_LOSS_RATE_MONTH_TREND.getAppToken();
			String monthlyTrendTableId = FeiShuDocumentEnum.CONTRACT_LOSS_RATE_MONTH_TREND.getTableId();
			String weeklyTrendAppToken = FeiShuDocumentEnum.CONTRACT_LOSS_RATE_WEEK_TREND.getAppToken();
			String weeklyTrendTableId = FeiShuDocumentEnum.CONTRACT_LOSS_RATE_WEEK_TREND.getTableId();

			// 2. 执行日详情、趋势表的查询数据并覆盖
			List<LarkContractLoseRateTrendVO> dataSources = elevatorContractService.getLarkContractLoseRateTrendList();
			contractLoseRateTrendSendToLark(dailyAppToken, dailyTableId, dailyTrendAppToken, dailyTrendTableId, dataSources);

			// 3. 若今天是周一，则执行周详情、趋势表的查询数据并覆盖
			Date today = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(today);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
			// 这个方法的周一是从2开始，周日是1
			if(dayOfWeek == 2){
				contractLoseRateTrendSendToLark(weeklyAppToken, weeklyTableId, weeklyTrendAppToken, weeklyTrendTableId,dataSources);
			}
			// 4. 若今天是每个月第1天，则执行月详情、趋势表的查询数据并覆盖
			int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
			if(dayOfMonth == 1){
				contractLoseRateTrendSendToLark(monthlyAppToken, monthlyTableId, monthlyTrendAppToken, monthlyTrendTableId,dataSources);
			}
			XxlJobHelper.handleSuccess("定时任务覆盖宇航的丢保率表-[执行]成功");
		}catch (Exception e){
			XxlJobHelper.handleSuccess("定时任务覆盖宇航的丢保率表-[执行]失败"+e);
		}

	}


	/**
	 * 及时率共用覆盖方法
	 */
	private void contractContinueTimelinessSendToLark(String appToken, String tableId, List<LarkContractContinueTimelinessVO> dataSources){

		if(Func.isEmpty(dataSources)){
			return;
		}
		// 数据处理
		Date today = new Date();
		FeiShuBatchDTO feishuBatchDTO = new FeiShuBatchDTO();
		List<FeiShuFieldsDTO> records = new ArrayList<>();
		for (LarkContractContinueTimelinessVO d : dataSources) {
			FeiShuFieldsDTO element = new FeiShuFieldsDTO();
			Map<String, Object> elementMap = new HashMap<>(30);
			// 1. 封装公共字段
			elementMap.put("唯一ID",d.getId());
			elementMap.put("续签状态-数据",d.getIsContinue());
			elementMap.put("项目ID",d.getBuildingId());
			elementMap.put("项目信息",d.getBuildingName());
			elementMap.put("电梯ID",d.getElevatorId());
			elementMap.put("电梯位置",d.getElevatorAddress());
			elementMap.put("年审标签",d.getUseType());
			elementMap.put("在保状态-数据",d.getMaintainStatus());
			elementMap.put("外包状态-数据",d.getFromType());
			elementMap.put("当前生效且需续签合同编号（该电梯无下份合同） ID",d.getContractId());
			elementMap.put("当前生效且需续签合同编号（该电梯无下份合同）",d.getContractNo());
			elementMap.put("需续签-合同质保标签",d.getIsQuaGuarantee());
			if(!Func.isNull(d.getContractBeginTime())){
				elementMap.put("需续签-合同开始时间",d.getContractBeginTime().getTime());
			}
			if(!Func.isNull(d.getContractRealendTime())) {
				elementMap.put("需续签-合同结束时间", d.getContractRealendTime().getTime());
			}
//			elementMap.put("需续签-合同地址链接",d.getLinkUrl());
			// 2025-03-31 字段类型变更：文本->链接
			if(Func.isNotBlank(d.getLinkUrl())){
				String linkUrl = d.getLinkUrl();
				Map<String, String> linkMap = new HashMap<>(2);
				linkMap.put("link", linkUrl);
				linkMap.put("text", "需续签-合同地址链接");
				elementMap.put("需续签-合同地址链接", linkMap);
			}
			elementMap.put("续签合同ID",d.getLastContractId());
			elementMap.put("续签合同合同编号（下份合同信息）",d.getLastContractNo());
			elementMap.put("续签-合同质保标签",d.getLastIsQuaGuarantee());
			if(!Func.isNull(d.getCreateTime())) {
				elementMap.put("续签-合同创建时间", d.getCreateTime().getTime());
			}
			if(!Func.isNull(d.getLastContractBeginTime())){
				elementMap.put("续签-合同开始时间",d.getLastContractBeginTime().getTime());
			}
			if(!Func.isNull(d.getLastContractRealendTime())){
				elementMap.put("续签-合同结束时间",d.getLastContractRealendTime().getTime());
			}
//			elementMap.put("续签-合同地址链接",d.getLastLinkUrl());
			// 2025-03-31 字段类型变更：文本->链接
			String lastLink = d.getLastLinkUrl();
			if(Func.isNotBlank(lastLink)){
				Map<String, String> lastLinkMap = new HashMap<>(2);
				lastLinkMap.put("link", lastLink);
				lastLinkMap.put("text", "续签-合同地址链接");
				elementMap.put("续签-合同地址链接", lastLinkMap);
			}
			elementMap.put("统计维度-日",d.getRecordDate().getTime());
			// 2. 封装特有字段
			if(FeiShuDocumentEnum.CONTRACT_CONTINUE_DAY_DETAIL.getTableId().equals(tableId)){
				elementMap.put("数据获取时间",today.getTime());
				elementMap.put("续签及时状态-数据",d.getContractOnTimeStatusDay());
				elementMap.put("周期内状态-数据",d.getIsContinueDay());
			}else if(FeiShuDocumentEnum.CONTRACT_CONTINUE_WEEK_DETAIL.getTableId().equals(tableId)) {
				// 获取这一周的第一天
				Date firstDay = DateUtil.beginOfWeek(d.getRecordDate());
				Date lastDay = DateUtil.endOfWeek(d.getRecordDate());
				String weekDesc = DateUtil.format(firstDay, "yyyy-MM-dd") + "-" + DateUtil.format(lastDay, "yyyy-MM-dd");
				elementMap.put("统计维度【周】", weekDesc);
				elementMap.put("数据获取时间",today.getTime());
				elementMap.put("周-最后日",lastDay.getTime());
				elementMap.put("续签及时状态-数据",d.getContractOnTimeStatusWeek());
				elementMap.put("周期内状态-数据",d.getIsContinueWeek());
			}else{
				// 获取这一月是哪个月
				Date recordDate = d.getRecordDate();
				String monthDesc = DateUtil.format(recordDate, "yyyy-MM");
				Date lastDay = DateUtil.endOfMonth(d.getRecordDate());
				elementMap.put("统计维度【月】", monthDesc);
				elementMap.put("月-最后日",lastDay.getTime());
				elementMap.put("统计维度数据获取时间",today.getTime());
				elementMap.put("续签及时状态-数据",d.getContractOnTimeStatusMonth());
				elementMap.put("周期内状态-数据",d.getIsContinueMonth());
			}
			element.setFields(elementMap);
			records.add(element);
		}
		feishuBatchDTO.setRecords(records);
		String result = feiShuDocumentService.commandCoverBatch(appToken, tableId, feishuBatchDTO);
		String message = "定时覆盖" + FeiShuDocumentEnum.getDescription(appToken, tableId) + "结果：" + result;
		feiShuDocumentService.commandSendGroupMessage(appToken, tableId, message);
	}

	/**
	 * 丢保率详情及丢保率趋势公用覆盖方法
	 */
	private void contractLoseRateTrendSendToLark(String detailAppToken, String detailTableId, String trendAppToken, String trendTableId, List<LarkContractLoseRateTrendVO> dataSources){
		// 1. 数据校验与数据准备：校验传参是否为空，若是，抛出异常，若否，查询数据并准备处理
		// 1.1 校验参数是否为空
		if(Func.isBlank(detailAppToken) && Func.isBlank(detailTableId) && Func.isBlank(trendAppToken) && Func.isBlank(trendTableId)){
			throw new ServiceException("飞书表格 参数不能为空");
		}
		// 1.2 查询数据并处理，若数据列表为空，则直接返回，否则，处理数据

		if(Func.isEmpty(dataSources)){
			return;
		}
		// 获取昨天的23:59:59
		Date yesterday = DateUtil.offsetDay(new Date(), -1);
		Date yesterdayEnd = DateUtil.endOfDay(yesterday);

		// 趋势数据封装
		Map<String, Object> trendRecords = new HashMap<>(7);
		long historyLoseCount = dataSources.stream().filter(t -> "历史脱保".equals(t.getLoseType())).count();
		long rangeContinueCount = dataSources.stream().filter(t -> "统计周期内脱保".equals(t.getLoseType())).count();
		long loseMaintainCount = dataSources.stream().filter(t -> "脱保".equals(t.getMaintainStatus())).count();
		int maintainCount = dataSources.size() - (int) loseMaintainCount;
		// 统计维度封装
		if(FeiShuDocumentEnum.CONTRACT_LOSS_DAY_DETAIL.getTableId().equals(detailTableId)){
			trendRecords.put("统计维度", DateUtil.format(yesterdayEnd, "yyyy-MM-dd"));
		}else if(FeiShuDocumentEnum.CONTRACT_LOSS_WEEK_DETAIL.getTableId().equals(detailTableId)){
			// 获取这一周的第一天
			Date firstDay = DateUtil.beginOfWeek(yesterday);
			String weekDesc = DateUtil.format(firstDay, "yyyy-MM-dd") + "-" + DateUtil.format(yesterdayEnd, "yyyy-MM-dd");
			trendRecords.put("统计维度", weekDesc);
			trendRecords.put("统计维度最后一日",yesterdayEnd.getTime());
		}else{
			trendRecords.put("统计维度",DateUtil.format(yesterdayEnd,"yyyy-MM"));
			trendRecords.put("统计维度最后一日",yesterdayEnd.getTime());
		}
		trendRecords.put("历史脱保梯台数", historyLoseCount);
		trendRecords.put("统计周期内脱保梯台数", rangeContinueCount);
		trendRecords.put("脱保梯台数", loseMaintainCount);
		trendRecords.put("在保梯台数", maintainCount);
		// 2. 封装并执行覆盖、新增动作
		// 2.1 数据封装：先封装公共字段，再根据detailTableId不同封装特有字段
		FeiShuBatchDTO feishuBatchDTO = new FeiShuBatchDTO();
		List<FeiShuFieldsDTO> records = new ArrayList<>();
		for (LarkContractLoseRateTrendVO d : dataSources) {
			FeiShuFieldsDTO element = new FeiShuFieldsDTO();
			Map<String, Object> elementMap = new HashMap<>(30);
			// 公共字段
			elementMap.put("唯一ID",d.getId());
			elementMap.put("数据获取时间",yesterdayEnd.getTime());
			elementMap.put("统计维度",d.getRecordDate().getTime());
			elementMap.put("项目ID",d.getBuildingId());
			elementMap.put("项目信息",d.getBuildingName());
			elementMap.put("电梯ID",d.getElevatorId());
			elementMap.put("电梯位置",d.getElevatorAddress());
			elementMap.put("年审标签",d.getUseType());
			if(!Func.isNull(d.getStopTime())){
				elementMap.put("操作完成脱保时间",d.getStopTime().getTime());
			}
			elementMap.put("导入-合同ID",d.getContractId());
			elementMap.put("导入-合同编号",d.getContractNo());
			elementMap.put("导入-合同标签（质保&非质保）",d.getIsQuaGuarantee());
			if(!Func.isNull(d.getStartTime())){
				elementMap.put("导入-合同开始时间",d.getStartTime());
			}
			if(!Func.isNull(d.getEndTime())){
				elementMap.put("导入-合同结束时间",d.getEndTime().getTime());
			}
			if (!Func.isNull(d.getEndTime())){
				if(Func.isNotBlank(d.getLinkUrl())) {
					Map<String, String> linkMap = new HashMap<>(2);
					String linkUrl = d.getLinkUrl();
					linkMap.put("link", linkUrl);
					linkMap.put("text", "导入-梯无忧合同地址");
					elementMap.put("导入-梯无忧合同地址", linkMap);
				}
			}
			// 特有字段
			if(FeiShuDocumentEnum.CONTRACT_LOSS_DAY_DETAIL.getTableId().equals(detailTableId)){
				elementMap.put("日-在保/脱保标记", d.getMaintainStatus());
				elementMap.put("日-脱保分类", d.getLoseType());
			}else if(FeiShuDocumentEnum.CONTRACT_LOSS_WEEK_DETAIL.getTableId().equals(detailTableId)){
				elementMap.put("周-在保/脱保标记", d.getMaintainStatus());
				elementMap.put("周-脱保分类", d.getLoseType());
				// 获取yesterday所在周的第一天
				Date firstDay = DateUtil.beginOfWeek(yesterday);
				String weekDesc = DateUtil.format(firstDay, "yyyy-MM-dd") + "-" + DateUtil.format(yesterdayEnd, "yyyy-MM-dd");
				elementMap.put("统计维度【周】", weekDesc);
			}else{
				elementMap.put("月-在保/脱保标记", d.getMaintainStatus());
				elementMap.put("月-脱保分类", d.getLoseType());
				// 获取yesterday所在的月
				String monthDesc = DateUtil.format(yesterday, "yyyy-MM");
				elementMap.put("统计维度【月】", monthDesc);
			}
			element.setFields(elementMap);
			records.add(element);
		}
		feishuBatchDTO.setRecords(records);
		String detailResult = feiShuDocumentService.commandCoverBatch(detailAppToken, detailTableId, feishuBatchDTO);
		String message = "定时覆盖" + FeiShuDocumentEnum.getDescription(detailAppToken, detailTableId) + "结果：" + detailResult;
		feiShuDocumentService.commandSendGroupMessage(detailAppToken, detailTableId, message);
		// 2.2 详情表覆盖动作
		// 2.3 趋势表仅新增动作
		FeiShuBatchDTO trendTableBatchDTO = new FeiShuBatchDTO();
		List<FeiShuFieldsDTO> trendTableRecords = new ArrayList<>();
		FeiShuFieldsDTO trendTableElement = new FeiShuFieldsDTO();
		trendTableElement.setFields(trendRecords);
		trendTableRecords.add(trendTableElement);
		trendTableBatchDTO.setRecords(trendTableRecords);
		String result = feiShuDocumentService.commandAddBatchLimit(trendAppToken, trendTableId, trendTableBatchDTO);
		message = "定时新增" + FeiShuDocumentEnum.getDescription(trendAppToken, trendTableId) + "结果：" + result;
		feiShuDocumentService.commandSendGroupMessage(trendAppToken, trendTableId, message);
	}

}
